<template>
  <div id="Merchant">
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic/home">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/merchant">页面</a>
            <span class="breadcrumb-item active" aria-current="page">商户</span>
          </nav>
          <h1>{{title}}</h1>
        </div>
      </div>
    </section>

    <section class="py-5">
      <div class="container-lg">
        <div class="row g-5">
          <el-card v-if="merchantTag === 'S001-1'" class="box-card" style="width: 100%;height: 100%">
            <div slot="header">
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-upload
                      class="avatar-uploader"
                      ref="upload"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      @click.native.prevent> <!-- 阻止默认点击行为 -->
                    <div class="grid-content bg-purple">
                      <el-avatar slot="trigger" :size="90" :src="img" @error="errorHandler" @click.native="handleAvatarClick" style="margin: 0 auto">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                      </el-avatar>
                    </div>
                  </el-upload>
                  <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
                </el-col>
              </el-row>
            </div>
            <el-form ref="form" :model="merchantForm" :rules="rules" label-width="100px">
              <el-form-item label="店长姓名" prop="name">
                <el-input v-model="merchantForm.name"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="merchantForm.phone"></el-input>
              </el-form-item>
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="merchantForm.idCard"></el-input>
              </el-form-item>
              <el-form-item label="店铺名称" prop="shopName">
                <el-input v-model="merchantForm.shopName"></el-input>
              </el-form-item>
              <el-form-item label="商铺类型" prop="shopType">
                <el-select v-model="merchantForm.shopType" placeholder="请选择商铺类型">
                  <el-option label="餐饮" value="1"></el-option>
                  <el-option label="零售" value="2"></el-option>
                  <el-option label="服务" value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="地址" prop="Addr">
                <el-input v-model="merchantForm.Addr"></el-input>
                <el-button type="primary" @click="handleAddress">选择地址</el-button>
              </el-form-item>

              <el-form-item>
<!--                <el-button type="primary" @click="updateUser=true">取消</el-button>-->
                <el-button type="primary" @click="submitUpload">申请</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-card v-if="merchantTag === 'S001-2'" class="box-card" style="width: 100%;height: 100%">
            <span><i class="el-icon-loading"></i>审核中...</span>
          </el-card>
          <el-card v-if="merchantTag === 'S001-3'" class="box-card" style="width: 100%;height: 100%">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="商户详情" name="first">
                <el-card v-if="updateMerchant === false" class="box-card" style="width: 100%;height: 100%">
                  <div slot="header">
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <div class="grid-content bg-purple">
                          <el-avatar :size="90" :src="'http://localhost:90'+merchant.shopImg" @error="errorHandler"  style="margin: 0 auto">
                            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                          </el-avatar>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                  <el-descriptions  class="margin-top" title="商户信息" :column="2"  border>
                    <template slot="extra">
                      <el-button type="primary" size="small" @click="updateMerchant = true">更新</el-button>
                    </template>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        店长姓名
                      </template>
                      {{merchant.name}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user-solid"></i>
                        商铺名称
                      </template>
                      {{merchant.shopName}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        手机号
                      </template>
                      {{merchant.phone}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        余额
                      </template>
                      {{merchant.balance}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-s-shop"></i>
                        门店类型
                      </template>
                      {{shopType(merchant.shopType)}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-s-shop"></i>
                        门店状态
                      </template>
                      {{ merchant.onOff === 1 ? '营业中' : '歇业中' }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-location-outline"></i>
                        生活地址
                      </template>
                      {{merchant.address}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        详细地址
                      </template>
                      {{merchant.detailAddress}}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
                <el-card v-if="updateMerchant === true" class="box-card" style="width: 100%;height: 100%">
                  <div slot="header">
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <el-upload
                            class="avatar-uploader"
                            ref="upload"
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            @click.native.prevent> <!-- 阻止默认点击行为 -->
                          <div class="grid-content bg-purple">
                            <el-avatar slot="trigger" :size="90" :src="img" @error="errorHandler" @click.native="handleAvatarClick" style="margin: 0 auto">
                              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                            </el-avatar>
                          </div>
                        </el-upload>
                        <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
                      </el-col>
                    </el-row>
                  </div>
                  <el-form ref="form" :model="merchantForm" :rules="rules" label-width="100px">
                    <el-form-item label="店长姓名" prop="name">
                      <el-input v-model="merchantForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="merchantForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="idCard">
                      <el-input v-model="merchantForm.idCard"></el-input>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="shopName">
                      <el-input v-model="merchantForm.shopName"></el-input>
                    </el-form-item>
                    <el-form-item label="商铺类型" prop="shopType">
                      <el-select v-model="merchantForm.shopType" placeholder="请选择商铺类型">
                        <el-option label="餐饮" value="1"></el-option>
                        <el-option label="零售" value="2"></el-option>
                        <el-option label="服务" value="3"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="地址" prop="Addr">
                      <el-input v-model="merchantForm.Addr"></el-input>
                      <el-button type="primary" @click="handleAddress">选择地址</el-button>
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="updateMerchant=false">取消</el-button>
                      <el-button type="primary" @click="submitUpload">更新</el-button>
                      <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="订单管理" name="second">
                <MerchantOrder />
              </el-tab-pane>
            </el-tabs>
          </el-card>
          <el-dialog title="地址" :visible.sync="showAddressDialog" width="80%" >
            <div style="height: 450px">
              <Map ref="map" @updateLocation="updateLocation" />
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showAddressDialog = false">取 消</el-button>
              <el-button type="primary" @click="setMapAddrToAddress">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import Map from "@/components/OrganicBody/AMapSearch.vue";
import MerchantOrder from "@/components/OrganicBody/Merchant-children/MerchantOrder.vue";
export default {
  name: 'MerchantBody',
  components: {MerchantOrder, Map },
  props: {},
  data() {
    return {
      title: '商户',
      updateMerchant: false,
      user: {},
      merchant: {},
      merchantTag: "",
      img: '',
      merchantForm: {
        name: '',
        phone: '',
        idCard: '',
        shopName: '',
        shopType: '', // 新增字段：商铺类型
        address: '',
        detailAddress: '',
        Addr: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入店长姓名', trigger: 'blur' },
          { min: 2, max: 30, message: '店长姓名长度应在2到30个字符之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/, message: '请输入有效的身份证号', trigger: 'blur' }
        ],
        shopName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 2, max: 30, message: '店铺名称长度应在2到30个字符之间', trigger: 'blur' }
        ],
        shopType: [
          { required: true, message: '请选择商铺类型', trigger: 'change' }
        ],
        Addr: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 2, max: 100, message: '地址长度应在2到100个字符之间', trigger: 'blur' }
        ],
      },
      MapAddr: '',
      fileList: [],
      showAddressDialog: false,
      activeName: 'first'
    }
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    intUser() {
      this.user = this.$store.state.user;
      // eslint-disable-next-line no-empty
      if (this.user.merchantTag === "S001-3") {
        this.merchant = this.$store.state.merchant;
        this.merchantTag = "S001-3";
        this.title = "商户详情";
        // eslint-disable-next-line no-empty
      } else if (this.user.merchantTag === "S001-2") {
        this.merchantTag = "S001-2";
        this.title = "审核中";
      } else {
        this.merchantTag = "S001-1";
        this.title = "商户申请";
      }
    },
    errorHandler() {
      return true;
    },
    handleAvatarClick() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt500KB = file.size / 1024 < 500;

        if (!isJPGOrPNG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
          return;
        }
        if (!isLt500KB) {
          this.$message.error('上传图片大小不能超过 500KB!');
          return;
        }

        this.img = URL.createObjectURL(file);
        this.fileList = [{ name: file.name, url: this.img, raw: file }];
      }
    },
    submitUpload() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请上传头像图片');
            return;
          }

          let formData = new FormData();
          formData.append('consumerId', this.user.consumerId);
          formData.append('balance',this.user.balance)
          formData.append('name', this.merchantForm.name);
          formData.append('phone', this.merchantForm.phone);
          formData.append('idCard', this.merchantForm.idCard);
          formData.append('shopName', this.merchantForm.shopName);
          formData.append('shopType', this.merchantForm.shopType);
          formData.append('address', this.merchantForm.address);
          formData.append('detailAddress', this.merchantForm.detailAddress);
          formData.append('lng', this.MapAddr.lon);
          formData.append('lat', this.MapAddr.lat);
          if(this.merchant.merchantId !== null && this.merchant.merchantId !== undefined){
            formData.append('merchantId', this.merchant.merchantId);
          }

          this.fileList.forEach(file => {
            formData.append('files', file.raw);
          });

          this.$axios.post('http://localhost:8090/merchant/saveMerchant', formData).then(({ data }) => {
            if (data !== null && data !== undefined) {
              this.$notify({
                title: '正在申请',
                message: '正在申请成为商户！' + data.shopName,
                type: 'success'
              });
              this.merchantTag = "S001-2";
              this.title = "审核中";
            }
            console.log(data);
          }).catch(error => {
            this.$notify({
              title: '更新失败',
              message: '申请失败，请稍后重试',
              type: 'warning'
            });
            console.error(error);
          });
        } else {
          // this.$message.error('请检查表单输入是否正确');
          this.$notify({
            title: '更新失败',
            message: '请检查表单输入是否正确',
            type: 'warning'
          });
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.img = '';
      this.fileList = [];
    },
    handleAddress() {
      this.showAddressDialog = true;
    },
    setMapAddrToAddress() {
      let address = this.MapAddr.province + '-' + this.MapAddr.city + '-' + this.MapAddr.district;
      let detailAddress = this.MapAddr.orgAddr;
      this.merchantForm.address = address;
      this.merchantForm.detailAddress = detailAddress;
      this.merchantForm.Addr = address + '-' + detailAddress+this.merchantForm.shopName;
      this.showAddressDialog = false;
    },
    // 点击地图后得到位置信息
    updateLocation(Addr) {
      this.MapAddr = Addr;
      console.log(this.MapAddr);
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    shopType(type){
      // eslint-disable-next-line no-empty
      if( type === 1 ) {
        return "宝妈/团长"
        // eslint-disable-next-line no-empty
      }else if( type === 2) {
        return "驿站/快递点";
        // eslint-disable-next-line no-empty
      }else if( type === 3) {
        return "超市/便利点";
      }else {
        return "其他"
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.intUser();
  },
  // 生命周期 - 创建之前
  beforeCreate() {},
  // 生命周期 - 挂载之前
  beforeMount() {},
  // 生命周期 - 更新之前
  beforeUpdate() {},
  // 生命周期 - 更新之后
  updated() {},
  // 生命周期 - 销毁之前
  beforeDestroy() {},
  // 生命周期 - 销毁完成
  destroyed() {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated() {}
}
</script>

<style scoped>
.box-card {
  margin: 3% auto;
  width: 85%;
}
.info-card-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.info-card {
  width: 48%;
  background-color: #f9f9f9;
}

.card-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.label {
  font-weight: bold;
  color: #666;
}

.value {
  color: #333;
}

@media (max-width: 768px) {
  .info-card-container {
    flex-direction: column;
  }

  .info-card {
    width: 100%;
  }
}
</style>
